<script lang="ts">
    import { onMount } from "svelte";
    import { useClassList } from "../utils/useClassList";
    import type { MessageProps } from "./Message";
    import Loading from "../Common/Loading/Loading.svelte";
    import Icon from "../Common/Icons/Icon.svelte";
    import { useStyle } from "../utils/useStyle";
    import { fly } from "svelte/transition";

    const props: MessageProps = $props();
    let visible = $state(false);
    const data = props.data;
    const classList = $derived(
        useClassList(data, "cm-message", {
            "cm-message-visible": visible,
            [`cm-message-${data.type}`]: data.type,
            "cm-message-background": data.background,
        }),
    );

    onMount(() => {
        // 设置效果
        setTimeout(() => {
            visible = true;
        });
        let duration = data.duration;
        if (duration === undefined || duration === null) {
            duration = 4;
        }

        if (duration) {
            setTimeout(() => {
                hide();
            }, duration * 1000);
        }
    });

    export const hide = () => {
        // 隐藏效果
        visible = false;
    };

    const onClose = () => {
        props.onclose?.(props.data.key);
    };

    const style = $derived(useStyle(data, { transform: `translate3d(0px, 0px, ${-props.index * 10}px)` }));
</script>

{#snippet getIcon(type?: string)}
    {#if type === "info"}
        <Icon icon="info" class="cm-message-icon" size={19} />
    {/if}
    {#if type === "success"}
        <Icon icon="checkCircle" class="cm-message-icon" size={19} />
    {/if}
    {#if type === "warning"}
        <Icon icon="warning" class="cm-message-icon" size={19} />
    {/if}
    {#if type === "error"}
        <Icon icon="xCircle" class="cm-message-icon" size={19} />
    {/if}
{/snippet}

{#if visible}
    <div class="cm-message-wrapper">
        <div class={classList} {style} in:fly={{ y: -20 }} out:fly={{ y: -20 }} onoutroend={onClose}>
            <div class="cm-message-inner">
                {#if data.loading}
                    <Loading />
                {:else if data.icon}
                    {@render data.icon(data)}
                {:else}
                    {@render getIcon(data.type)}
                {/if}
                <div class="cm-message-content">
                    {data.content}
                </div>
                {#if data.closeable}
                    <div class="cm-message-close" onclick={hide}>
                        {#if data.closeIcon}
                            {@render data.closeIcon()}
                        {:else}
                            <Icon icon="times" class="cm-message-close-icon" size={14} />
                        {/if}
                    </div>
                {/if}
            </div>
        </div>
    </div>
{/if}
